var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.locals.user = req.session.user||"";
  console.log(req.session.user);
  res.locals.firstnum = Math.round(Math.random()*10);
  req.session.firstnum = res.locals.firstnum;
  res.locals.secondnum = Math.round(Math.random()*10);
  req.session.secondnum = res.locals.secondnum;
  res.render("users");
});

var users = {}

router.get("/logout",function(req,res){
  req.session.user = undefined;
  res.redirect("back");
});

router.post("/login",function(req,res){
  const {loginname,password ,vnum} = req.body;
  if(Number(vnum) === (req.session.firstnum + req.session.secondnum) && users[loginname] && users[loginname].password === password){
    req.session.user = {loginname}
  }
  res.redirect("back");
});

router.get("/reg",function(req,res){
  res.locals.thirdnum = Math.round(Math.random()*10);
  req.session.thirdnum = res.locals.thirdnum;
  res.locals.fourthnum = Math.round(Math.random()*10);
  req.session.fourthnum = res.locals.fourthnum;
  res.render("zhuce");
});

router.post("/reg",function(req,res){
  const {loginname , password , confirm,xnum} = req.body;
  if(Number(xnum) === (req.session.thirdnum + req.session.fourthnum) && loginname && password && password === confirm){
    users[loginname] = {loginname,password};
    res.redirect("/users");
  }else {
    res.redirect("back");
  }

});

module.exports = router;
